package com.badminton.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
@Component
public class TraceFilter extends OncePerRequestFilter {
    private static final String TRACE_ID_KEY = "traceId";
    private static final String REQUEST_TRACE_ID = "Trace-Request";
    private static final String RESPONSE_TRACE_ID = "Trace-Response";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");	//从 http 请求头中取出 token
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String apiUrl = request.getRequestURI();
        try {
            String responseTraceId;
            String requestTraceId = request.getHeader(REQUEST_TRACE_ID);
            if (StringUtils.isEmpty(requestTraceId)) {
                responseTraceId = traceStart();
            } else {
                responseTraceId = traceStart(requestTraceId);
            }
            response.addHeader(RESPONSE_TRACE_ID, responseTraceId);
            filterChain.doFilter(request, response);
        } finally {
            stopWatch.stop();

            //去掉性能相关日志
            if(!apiUrl.contains("/actuator")){
                log.info("web api [{}] execute finished,totally cost {} ms!", apiUrl, stopWatch.getTotalTimeMillis());
            }

            traceEnd();
        }
    }

    public static String traceStart() {
        String traceId = generateTraceId();
        return traceStart(traceId);
    }

    public static String traceStart(String traceId) {
        MDC.put(TRACE_ID_KEY, traceId);
        return traceId;
    }

    public static void traceEnd() {
        MDC.clear();
    }

    /**
     * 生成跟踪ID
     *
     * @return
     */
    private static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }
}